<template>
    <div class="edit-userinfo-part-div">

       <el-row type="flex" justify="'center">
           <el-col :span="24">
               <el-form ref="form" :model="form" size="medium" :rules="rules" status-icon>
                    <el-row class="form-row" type="flex" justify="center">
                        <el-col :span="18">
                            <el-form-item label="用户名" prop="userName">
                                <!--也许需要不能修改用户名或者默认显示本身用户名-->
                                <el-input v-model.trim="form.userName" placeholder="请输入用户名"></el-input>
                            </el-form-item>
                            <!--<el-form-item label="密码" prop="password">
                                <el-input type="password" v-model.trim="form.password" placeholder="请输入密码"></el-input>
                            </el-form-item>
                            <el-form-item label="确认密码" prop="checkPassword">
                                <el-input type="password" v-model.trim="form.checkPassword" placeholder="请再次输入密码"></el-input>
                            </el-form-item>-->
                            <el-form-item label="真实姓名" prop="userRealName">
                                <el-input class="realname" v-model.trim="form.userRealName" placeholder="请输入真实姓名"></el-input>
                            </el-form-item>
                            <el-form-item label="身份证号" prop="idCard">
                                <el-input v-model.trim="form.idCard" placeholder="请输入身份证号"></el-input>
                            </el-form-item>
                            <el-form-item label="微信号" prop="wechatCode">
                                <el-input v-model.trim="form.wechatCode" placeholder="请输入微信号"></el-input>
                            </el-form-item>
                            <el-form-item label="手机号" prop="phoneNum">
                                <el-input v-model.number.trim="form.phoneNum" placeholder="请输入手机号"></el-input>
                            </el-form-item>
                            <el-form-item label="邮箱" prop="mailAddr">
                                <el-input v-model.trim="form.mailAddr" placeholder="请输入邮箱"></el-input>
                            </el-form-item>
                            <el-form-item label="就读学校" prop="schoolName">
                                <el-input v-model.trim="form.schoolName" placeholder="请输入就读学校"></el-input>
                            </el-form-item>
                            <el-form-item label="学号" prop="studentNum">
                                <el-input  v-model.number.trim="form.studentNum" placeholder="请输入学号"></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button class="save-btn"@click="submit('form')" round size="'small">确认修改</el-button>

                            </el-form-item>
                        </el-col>
                    </el-row>
               </el-form>
           </el-col>
       </el-row>


    </div>
</template>

<script>

    import storage from '../../model/storage.js';

    export default {
        name: "EditUserInfoPart",
        data(){
            //用户名唯一
            var validateUsername = (rule, value, callback) => {
                if(value === this.$store.state.userInfo.userName){ callback();}
                else
                {
                    console.log("发送请求");
                axios.get('/validateUsernameAndPhoneNum', {
                    params: {
                        userName: value
                    }
                })
                    .then(response => {
                        if(response.data.success){
                            callback();
                        }else{
                            console.log(response);
                            callback(new Error(response.data.msg));
                        }
                    })
                    .catch(error => {
                        console.log(error);
                        callback(new Error());
                    })
                    .finally(() =>{
                    });
                }
            };



            var validatePass = (rule, value, callback) =>{
                if(value === ''){
                    callback(new Error('密码不能为空'));
                }else{
                    if(this.form.checkPassword !==''){
                        this.$refs.form.validateField('checkPassword');
                    }
                    callback();
                }
            };

            var validatePass2 = (rule, value, callback) => {
                if(value === ''){
                    callback(new Error('确认密码不能为空'));
                }else if(value !== this.form.password){
                    callback(new Error('两次输入的密码不一致！'));
                }else {
                    callback();
                }
            };

            var validateUserRealName= (rule, value, callback) => {
                if(value === ''){
                    callback();
                }else{
                    if(!/^.{2,40}$/.test(value)){
                        callback(new Error('真实名字长度应在4-40位之间'));
                    }else{
                        callback();
                    }
                }
            };

            var validateIdCard = (rule, value, callback) => {
                if(value === ''){
                    callback();
                }else{
                    if(!/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(value)){
                        callback(new Error('请输入正确的身份证'));
                    }else{
                        callback();
                    }
                }
            };

            //电话号码唯一
            var validatePhoneNum = (rule, value, callback) => {
                if(value === this.$store.state.userInfo.phoneNum){callback();}
                else{
                    axios.get('/validateUsernameAndPhoneNum',  {
                        params: {
                            phoneNum: value
                        }
                    })
                        .then(response => {
                            if(response.data.success){
                                callback();
                            }else{
                                console.log(response);
                                callback(new Error("手机号已存在，请重新填写"));
                            }
                        })
                        .catch(error => {
                            console.log(error);
                            callback(new Error());
                        })
                        .finally(  () => {

                        });
                }

            };

            //邮箱唯一
            var validateMailAddr = (rule, value, callback) => {
                if(value === this.$store.state.userInfo.mailAddr){callback();}
                else{
                    this.$axios.get('/validateUsernameAndPhoneNum',{
                        params: {
                            mailAddr: value
                        }
                    })
                        .then(response => {
                            if(response.data.success){
                                callback();
                            }else{
                                console.log(response);
                                callback(new Error("邮箱已存在，请重新填写。"));
                            }
                        })
                        .catch(error => {
                            console.log(error);
                            callback(new Error());
                        })
                        .finally( () =>{

                        });
                }

            };

            var validateSchoolName = (rule, value, callback) => {
                if(value === ''){
                    callback();
                }else{
                    if(!/^.{4,40}$/.test(value)){
                        callback(new Error('学校名称长度应在4-40位之间'));
                    }else{
                        callback();
                    }
                }
            };

            var validateStudentNum = (rule, value, callback) => {
                if(value === ''){
                    callback();
                }else{
                    if(!/^[0-9]{4,40}$/.test(value)){
                        callback(new Error('学号长度应为4-40位数字'));
                    }else{
                        callback();
                    }
                }
            };

            return{
                form:{
                    userName:"",
                    userRealName:"",
                    idCard:"",
                    wechatCode:"",
                    phoneNum:"",
                    mailAddr:"",
                    schoolName:"",
                    studentNum:""
                },
                rules:{
                    //触发器 blur失去焦点，change发生变化
                    //validator 自定义二次检验
                    userName: [
                        { required: true, message: '用户名不能为空', trigger: 'blur' },
                        { min: 2, max: 16, message: '用户名长度应在4-16位之间'},
                        { validator: validateUsername, trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '密码不能为空', trigger: 'blur' },
                        { pattern: /^[a-zA-Z0-9]{6,18}$/, message: '密码应由6-18位字母和数字组成，不包含特殊字符。',trigger:['blur','change']},
                        { validator: validatePass, trigger: 'blur' }
                    ],
                    checkPassword: [
                        { required: true, message: '确认密码不能为空', trigger: 'blur' },
                        { validator: validatePass2, trigger: 'blur' },
                    ],
                    userRealName: [
                        { validator: validateUserRealName, trigger: ['blur', 'change'] }
                    ],
                    idCard: [
                        { validator: validateIdCard, trigger: ['blur', 'change']}
                    ],
                    wechatCode: [
                        { required: true, message: '微信号不能为空', trigger: 'blur' },
                        { pattern: /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/, message: '请输入格式正确的微信号', trigger: ['blue', 'change']}
                    ],
                    phoneNum: [
                        { required: true, message: '手机号不能为空', trigger: 'blur' },
                        { pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号', trigger: ['blur', 'change']},
                        { validator: validatePhoneNum, trigger: 'blur' }
                    ],
                    mailAddr: [
                        { required: true, message: '邮箱不能为空', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']},
                        { validator: validateMailAddr, trigger: 'blur' }
                    ],
                    schoolName: [
                        { validator: validateSchoolName, trigger: ['blur', 'change']}
                    ],
                    studentNum: [
                        { validator: validateStudentNum, trigger: ['blur', 'change']}
                    ]
                }
            }
        },

        methods: {
            submit(formName){
                var formTemp = JSON.parse(JSON.stringify(this.form));
                var url = '/manage/updateUserInfo';
                console.log(formTemp);
                this.$refs[formName].validate((valid) => {

                    if(valid){
                        axios.post(
                            url,
                            formTemp
                             ).then(response => {
                                 if(response.data.success){
                                     storage.setSession("userInfo",response.data.data);
                                     this.$message.success("修改成功！");
                                     location.reload();
                                 }else{
                                     console.log("modify failed.");
                                 }
                            }).catch(error => {

                        });
                    }else{
                        console.log('error submit!');
                        return false;
                    }
                });
            }
        },
        mounted() {
            Object.assign(this.form, this.$store.state.userInfo);
        }


    }
</script>

<style scoped>

    .form-row {
        margin-top: 30px;
    }

    .save-btn{
        margin-left: 30%;
    }
</style>